<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 订单逻辑
 */
namespace app\allwin\widget;
use app\allwin\widget\Inform;
use app\allwin\model\CouponUser;     //用户优惠券
use app\allwin\model\CouponSubsidize;  //平台补贴优惠券
use app\allwin\model\Fund;  //基金
use app\allwin\model\MchIdQueen;  //队列
use app\allwin\model\MchId;  //商户号
use app\allwin\model\Bank;
use app\allwin\model\AllwinStore;
use app\allwin\model\BankBill;
use app\allwin\model\StoreBill;
use app\allwin\model\FundBill;

class Order{

    /**
     * 微信买单收益分账
     * @param array $order  订单信息
     * @return void
     */
    public static function income(array $order){
        $store = AllwinStore::where(['id' => $order['store_id']])->field('id,member_miniapp_id,charges,manage_uid,mch_id,name')->find();
        if(empty($store)){
            return;
        }
        //判断当前会员是否买单好店的用户体系,是当前好店的不分润
        $setting = model('AllwinConfig')->getConfig($store->member_miniapp_id);
        $is_profitsharing = false;
        if($setting->is_fees_types <= 1){
            if($setting->is_fees_types == 0){
                $is_profitsharing = true;
            }else{
                if($order['coupon_user_id']){
                    $is_profitsharing = true;
                }
            }
        }
        $default_charges       = $setting->default_charges/1000; //默认手续费
        $charges               = $default_charges;  //好店服务费
        $user_store_id         = 0;  //下单用户来自商家
        $user_store_manage_uid = 0;  //下单用户来自商家的管理员ID(用于奖励推荐开通会员的商家UID)
        $is_charges            = false;  //是否分润
        //判断是否这个店的会员
        if($store->charges > 0 && $is_profitsharing){
            $allwinUser = model('AllwinUser')->getUserStoreId($order['uid']);
            $user_store_id = empty($allwinUser) ? 0 : $allwinUser->store_id;
            if($user_store_id != $store->id){ 
                $user_store_manage_uid = empty($allwinUser->store) ? 0 : $allwinUser->store->manage_uid;  //好店老板UID
                $charges    = $store->charges/1000; //商家基础服务费
                $is_charges = true;  //分润
            }
        }
        /**
         * 计算金额
         * $order['store_amount']  好店应收金额
         * $order['order_amount']  实际支付金额
         */
        $wechat_charges_amout = money(abs($order['order_amount']*$default_charges));  //微信扣除的服务费(厘四舍五入到分)
        $income = 0;
        if($is_charges == true){
            $service_amount = money($order['store_amount']*$charges);
            $income         = money($service_amount-$wechat_charges_amout-0.01);  //分账的本金(不包含微信手续费,减去1分保证分账金额)
            $store_amount   = money($order['store_amount']-$service_amount);      //老板收入
        }else{
            $store_amount   = money($order['store_amount']-$wechat_charges_amout); //老板收入
        }
        if ($store_amount < 0){
          return;  //金额小于0 不结算
        }
        $queen = []; //分账队列参数
        if ($setting->is_psp == 0 || empty($store->mch_id)) {
            Bank::dueMoney($store->member_miniapp_id,$store->manage_uid,$store_amount);
            $msg = '结算到平台';
        }else{
            $msg = '结算到商户号';
        }
        if ($setting->is_wechat_profitsharing && $is_profitsharing){
            if($store->mch_id == 0){
                $mch = MchId::getMch(0,$store->member_miniapp_id);
                $store->mch_id = $mch->id;
            }
            $queen[] = [
                'member_miniapp_id' => $store->member_miniapp_id,
                'store_id'          => $store->id,
                'uid'               => 0,
                'mch_id'            => $store->mch_id,
                'amount'            => $store_amount*100,
                'transaction_id'    => $order['paid_no'],
                'out_order_no'      => $order['order_no'],
                'is_finish'         => 0,
                'types'             => 1,
                'msg'               => $msg,
            ];
        }
        StoreBill::add(['miniapp_id' => $store->member_miniapp_id,'uid' => $store->manage_uid,'store_id' => $store->id,'pay_uid' => $order['uid'],'money' => $store_amount],$msg);            //商家账单
        BankBill::add(['miniapp_id' => $store->member_miniapp_id,'uid' => $store->manage_uid,'store_id' => $store->id,'pay_uid' => $order['uid'],'money' => $store_amount],$msg);             //个人账单
        model('StoreStats')->payment($store,$store_amount);  //增加统计 
        //增加优惠券统计
        if($order['coupon_price'] > 0){
            model('StoreStats')->coupon($store,$order['coupon_price']);
        }
        //判断分账金额最小0.1元
        $nominate_money = 0;
        $agent_rebate   = 0;
        $store_rebate   = 0;
        $company_rebate = 0;
        $workers_rebate = 0;
        if($is_charges && $is_profitsharing && $income >= 0.1){
            //会员直推奖励
            $level = model('Levels')->where(['user_id' => $order['uid'],'level'=> 1])->find();
            if (!empty($level)) {
                $vip = model('Vip')->where(['user_id' => $level->parent_id,'is_lock' => 0,'state' => 1])->field('vipcard_id,user_id')->find();
                if(!empty($vip)){
                    if($vip->vipcard->is_tax){
                        $nominate_money = money($income*$vip->vipcard->nominate/100);
                        if($nominate_money > 0.01){
                            if($setting->is_wechat_profitsharing){
                                $queen[] = [
                                    'member_miniapp_id' => $store->member_miniapp_id,
                                    'store_id'          => $store->id,
                                    'uid'               => $level->parent_id,
                                    'mch_id'            => 0,
                                    'amount'            => $nominate_money*100,
                                    'transaction_id'    => $order['paid_no'],
                                    'out_order_no'      => $order['order_no'],
                                    'is_finish'         => 0,
                                    'types'             => 0,
                                    'msg'               => '['.$vip->vipcard->name.']推荐奖励',
                                ];
                            }else{
                                Bank::dueMoney($store->member_miniapp_id,$level->parent_id,(float)$nominate_money);
                                BankBill::add(['miniapp_id' => $store->member_miniapp_id,'store_id' => $store->id,'money' => $nominate_money,'uid'=> $level->parent_id,'pay_uid' => $order['uid']],'['.$vip->vipcard->name.']消费奖励');
                            }
                        }
                    }
                }
            }
            //社群主奖励
            if($setting->agent_rebate > 0){
                $agentuid = model('AllwinUserAgent')->agentUid($order['uid'],$store->member_miniapp_id);
                if($agentuid){
                    $agent_rebate = money($income*$setting->agent_rebate/100);
                    if ($agent_rebate > 0.01) {
                        if($setting->is_wechat_profitsharing){
                            $queen[] = [
                                'member_miniapp_id' => $store->member_miniapp_id,
                                'store_id'          => $store->id,
                                'uid'               => $agentuid,
                                'mch_id'            => 0,
                                'amount'            => $agent_rebate*100,
                                'transaction_id'    => $order['paid_no'],
                                'out_order_no'      => $order['order_no'],
                                'is_finish'         => 0,
                                'types'             => 0,
                                'msg'               => '[社群主]消费奖励',
                            ];
                        }else{
                            Bank::dueMoney($store->member_miniapp_id,$agentuid,(float)$agent_rebate);
                            BankBill::add(['miniapp_id' => $store->member_miniapp_id,'store_id' => $store->id,'money' => $agent_rebate,'uid'=> $agentuid,'pay_uid' =>$order['uid']],'[社群主]消费奖励');
                        }
                    }
                }
            }
            //判断分成用户所属商家ID
            if($user_store_manage_uid > 0){
                $store_rebate = money($income*$setting->store_rebate/100);
                if ($store_rebate > 0.01) {
                    if($setting->is_wechat_profitsharing){
                        $queen[] = [
                            'member_miniapp_id' => $store->member_miniapp_id,
                            'store_id'          => $store->id,
                            'uid'               => $user_store_manage_uid,
                            'mch_id'            => 0,
                            'amount'            => $store_rebate*100,
                            'transaction_id'    => $order['paid_no'],
                            'out_order_no'      => $order['order_no'],
                            'is_finish'         => 0,
                            'types'             => 0,
                            'msg'               => '[其它好店]买单奖励',
                        ];
                    }else{
                        $store_rebate_bill = [
                            'miniapp_id' => $store->member_miniapp_id,
                            'uid'        => $user_store_manage_uid,
                            'store_id'   => $allwinUser->store_id,
                            'pay_uid'    => $order['uid'],
                            'money'      => $store_rebate
                        ];
                        Bank::dueMoney($store->member_miniapp_id,$user_store_manage_uid,(float)$store_rebate);   //商家分润
                        StoreBill::add($store_rebate_bill,'[其它好店]买单奖励');  //商家账单
                        BankBill::add($store_rebate_bill,'[其它好店]买单奖励');   //个人账单
                    }
                }
            }
            //给合伙人
            if($setting->workers_rebate > 0){
                $worker = model('Worker')->whereRaw("FIND_IN_SET({$store->id},store_ids)")->field('uid')->find();
                if(!empty($worker)){
                    $workers_rebate = money($income*$setting->workers_rebate/100);
                    if ($workers_rebate > 0.01) {
                        if ($setting->is_wechat_profitsharing) {
                            $queen[] = [
                                'member_miniapp_id' => $store->member_miniapp_id,
                                'store_id'          => $store->id,
                                'uid'               => $worker->uid,
                                'mch_id'            => 0,
                                'amount'            => $workers_rebate*100,
                                'transaction_id'    => $order['paid_no'],
                                'out_order_no'      => $order['order_no'],
                                'is_finish'         => 0,
                                'types'             => 0,
                                'msg'               => '[合伙人]买单奖励',
                            ];
                        } else {
                            Bank::dueMoney($store->member_miniapp_id,$worker->uid,(float)$workers_rebate);
                            BankBill::add(['miniapp_id' => $store->member_miniapp_id,'store_id' => $store->id,'money' => $workers_rebate,'uid'=> $worker->uid,'pay_uid' =>$order['uid']], '[合伙人]买单奖励');
                        }
                    }
                }
            }
            //给归属公司分账
            if($store->city_id > 0){
                $city = model('City')->where(['id' => $store->city_id])->find();
                if (!empty($city)) {
                    $company_rebate = money($income*$setting->company_rebate/100);
                    if ($company_rebate > 0.01) {
                        if ($setting->is_wechat_profitsharing) {
                            //分账到商户号
                            $queen[] = [
                                'member_miniapp_id' => $store->member_miniapp_id,
                                'city_id'           => $store->city_id,
                                'store_id'          => $store->id,
                                'uid'               => 0,
                                'mch_id'            => $city->mch_id,
                                'amount'            => $company_rebate*100,
                                'transaction_id'    => $order['paid_no'],
                                'out_order_no'      => $order['order_no'],
                                'is_finish'         => 0,
                                'types'             => 1,
                                'msg'               => '[城市]买单奖励',
                            ];
                        } else {
                            $ompany_rebate_bill = [
                                'miniapp_id' => $store->member_miniapp_id,
                                'store_id'   => $store->id,
                                'city_id'    => $store->city_id,
                                'uid'        => $city->uid,
                                'pay_uid'    => $order['uid'],
                                'money'      => $company_rebate
                            ];
                            Bank::dueMoney($store->member_miniapp_id,$city->uid,(float)$company_rebate);   //商家分润
                            BankBill::add($ompany_rebate_bill, '[城市]买单奖励');   //个人账单
                            model('CityBill')->add($ompany_rebate_bill, '[城市]买单奖励');   //公司奖励
                        }
                    }
                }
            }
            //扣除运营费（给运营城市）
            $platform_money = money($income-($nominate_money+$agent_rebate+$store_rebate+$company_rebate+$workers_rebate));
            if($platform_money > 0.01){
                $mch = MchId::getMch(0,$store->member_miniapp_id);
                if (!empty($mch)) {
                    if($setting->is_wechat_profitsharing){
                        $queen[] = [
                            'member_miniapp_id' => $store->member_miniapp_id,
                            'store_id'          => $store->id,
                            'uid'               => 0,
                            'mch_id'            => $mch->id,
                            'amount'            => $platform_money*100,
                            'transaction_id'    => $order['paid_no'],
                            'out_order_no'      => $order['order_no'],
                            'is_finish'         => 0,
                            'types'             => 1,
                            'msg'               => '[运营公司]服务费结余',
                        ];
                    }else{
                        if(isset($mch->city->uid)){
                            $platform_rebate_bill = [
                                'miniapp_id' => $store->member_miniapp_id,
                                'store_id'   => $store->id,
                                'uid'        => $mch->city->uid,
                                'pay_uid'    => $order['uid'],
                                'money'      => $platform_money
                            ];
                            Bank::dueMoney($store->member_miniapp_id,$mch->city->uid,(float)$platform_money);   //商家分润
                            BankBill::add($platform_rebate_bill,'[运营公司]买单服务费结余');   //个人账单
                            model('CityBill')->add($platform_rebate_bill,'[运营公司]买单服务费结余');   //公司奖励
                        }
                    }
                }
            }
        }
        //平台优惠券
        $platform_amount = [];
        if(!empty($order['platform_amount']) && $is_profitsharing){
            $platform_amount = self::platform_amount($order,$store,$setting);
            if(!empty($platform_amount)){
                $queen = array_merge($queen,$platform_amount);
            }
        }
        //添加一个无需分账的队列
        if(empty($queen) && $setting->is_wechat_profitsharing && $is_profitsharing){
            $queen[] = [
                'member_miniapp_id' => $store->member_miniapp_id,
                'store_id'          => $store->id,
                'uid'               => 0,
                'mch_id'            => 0,
                'amount'            => 0,
                'transaction_id'    => $order['paid_no'],
                'out_order_no'      => $order['order_no'],
                'is_finish'         => 0,
                'types'             => 2,
                'msg'               => '无需分账,金额￥'.$store_amount,
            ];
        }
        //增加队列
        if(!empty($queen)){
            MchIdQueen::createQueen($queen);
        }
        //订单公众号模板通知
        if(!empty($setting->tplmsg_order)){
            Inform::order(['uid' => $store->manage_uid,'store_id' => $store->id,'store_name' => $store->name,'amount' => $order['store_amount'],'order_no' => $order['order_no'],'miniapp_id' => $store->member_miniapp_id,'tplmsg' => $setting->tplmsg_order]);
        }
        return true;
    }

    /**
     * 优惠券分配
     * @param  array   $store   [分配金额]
     * @param  object  $store   [店铺信息]
     * @param  object  $setting [配置信息]
     * @return array  
     */
    public static function platform_amount($order,$store,$setting){
        if(empty($order['platform_amount'])){
            return [];
        }
        $platform_amount = $order['platform_amount'];
        $city = model('City')->where(['id' => $store->city_id])->find();
        $queen = [];
        //分配优惠券利润给加盟城市
        $city_money = $platform_amount*$setting->city_rate/100;
        if($city_money >= 0.01){
            if(!empty($city)) {
                if ($setting->is_wechat_profitsharing) {
                    $queen[] = [
                        'member_miniapp_id' => $store->member_miniapp_id,
                        'city_id'           => $store->city_id,
                        'store_id'          => $store->id,
                        'uid'               => 0,
                        'mch_id'            => $city->mch_id,
                        'amount'            => $city_money*100,
                        'transaction_id'    => $order['paid_no'],
                        'out_order_no'      => $order['order_no'],
                        'is_finish'         => 0,
                        'types'             => 1,
                        'msg'               => '[城市]优惠券分润',
                    ];
                } else {
                    $bill = [
                        'miniapp_id' => $store->member_miniapp_id,
                        'store_id'   => $store->id,
                        'city_id'    => $store->city_id,
                        'uid'        => $city->uid,
                        'pay_uid'    => $order['uid'],
                        'money'      => $city_money
                    ];
                    Bank::dueMoney($store->member_miniapp_id,$city->uid,$city_money);   //商家分润
                    BankBill::add($bill,'[城市]优惠券分润');   //个人账单
                    model('CityBill')->add($bill,'[城市]优惠券分润');   //公司奖励
                }
            }
        }
        //分配优惠券给平台方
        $admin_money = empty($city->is_default) ? $platform_amount*($setting->admin_rate/100) : $platform_amount*(1-$setting->city_rate/100);
        if($admin_money >= 0.01){
            if ($setting->is_wechat_profitsharing) {
                $mch = MchId::getMch();
                $queen[] = [
                    'member_miniapp_id' => $store->member_miniapp_id,
                    'city_id'           => $store->city_id,
                    'store_id'          => $store->id,
                    'uid'               => 0,
                    'mch_id'            => $mch->id,
                    'amount'            => $admin_money*100,
                    'transaction_id'    => $order['paid_no'],
                    'out_order_no'      => $order['order_no'],
                    'is_finish'         => 0,
                    'types'             => 1,
                    'msg'               => '[平台]优惠券分润',
                ];
            }else{
                Bank::dueMoney($store->member_miniapp_id,$setting->admin_uid,$admin_money);   //商家分润
                BankBill::add(['uid' => $setting->admin_uid,'money' => $admin_money,'miniapp_id' => $store->member_miniapp_id,'store_id' => $store->id,'city_id' => $store->city_id,'pay_uid' => $order['uid']],'[城市]优惠券分润');   //个人账单
            }
        }
        //分配优惠券给运营公司
        if(empty($city->is_default)){
            $agent_money = $platform_amount*($setting->company_rate/100);
            if($agent_money >= 0.01){
                $agent_mch = MchId::getMch(0,$store->member_miniapp_id);
                if ($setting->is_wechat_profitsharing) {
                    $queen[] = [
                        'member_miniapp_id' => $store->member_miniapp_id,
                        'city_id'           => $store->city_id,
                        'store_id'          => $store->id,
                        'uid'               => 0,
                        'mch_id'            => $agent_mch->id,
                        'amount'            => $agent_money*100,
                        'transaction_id'    => $order['paid_no'],
                        'out_order_no'      => $order['order_no'],
                        'is_finish'         => 0,
                        'types'             => 1,
                        'msg'               => '[运营公司]优惠券分润',
                    ];
                } else {
                    $agent_bill = [
                        'miniapp_id' => $store->member_miniapp_id,
                        'store_id'   => $store->id,
                        'city_id'    => $store->city_id, 
                        'uid'        => $agent_mch->city->uid,
                        'pay_uid'    => $order['uid'],
                        'money'      => $agent_money
                    ];
                    Bank::dueMoney($store->member_miniapp_id,$agent_mch->city->uid,$agent_money);   //商家分润
                    BankBill::add($agent_bill, '[运营公司]优惠券分润');   //个人账单
                    model('CityBill')->add($agent_bill, '[运营公司]优惠券分润');   //公司奖励
                }
            }
        }
        return $queen;
    } 

    /**
     * 采购基金商户补贴
     * @param  array  $order [计算参数]
     * @return  boolean
     */
    public static function fund(array $order){
        if($order['coupon_user_id'] <= 0){
            return;
        }
        $condition['uid']               = $order['uid'];
        $condition['member_miniapp_id'] = $order['member_miniapp_id'];
        $condition['id']                = $order['coupon_user_id'];
        $rel = CouponUser::getuser($condition);
        if(empty($rel)){
            return;
        }
        $fund_coupon = CouponSubsidize::where(['coupon_id' => $rel->coupon_id])->find();
        if(empty($fund_coupon)){
            return;
        }
        if($fund_coupon->how_much <= 0){
            return;
        }
        $fund  = new Fund();
        $subsidy = $fund->subsidy($order['member_miniapp_id'],$fund_coupon->how_much);
        if($subsidy && $rel->store->manage_uid > 0){
            Bank::dueMoney($order['member_miniapp_id'],$rel->store->manage_uid,(float)$subsidy);  //结算利润
            model('StoreStats')->payment($order['member_miniapp_id'],$order['store_id'],$subsidy);  //增加统计
            $bill = [
                'miniapp_id' => $order['member_miniapp_id'],
                'store_id'   => $order['store_id'],
                'pay_uid'    => $order['uid'],
                'money'      => $subsidy,
                'order_no'   => $order['order_no'],
                'uid'        => $rel->store->manage_uid,
                'types'      => 1
            ];
            BankBill::add($bill,'消费补贴');   //个人账单
            StoreBill::add($bill,'消费补贴');  //商家账单
            FundBill::add($bill);             //补贴出账
        }
    }
}